package filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 此类用来判断用户是否已经登录，如果没有登录
 * 用户访问任何非登录页面，网站均跳转到登录页面
 * 若用户已登录，用户若访问没有权限的页面时
 * 会自动跳转到自己有权限的首页
 * 
 * @author Waiting_hao
 *
 */
public class CheckLogin implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest request = (HttpServletRequest)arg0;
		HttpServletResponse response = (HttpServletResponse)arg1;
		HttpSession session = request.getSession();
		String identity = (String) session.getAttribute("isLogin");

		/* 用户未登录 */
		if(identity == null){
			if(request.getRequestURI().indexOf("index.jsp")==-1){
				response.sendRedirect("/studormcms/index.jsp");
			}
			return;
		}else{
			int id = Integer.parseInt(identity);
			switch(id){
			case 1:
				if(request.getRequestURI().indexOf("admin")==-1){
					response.sendRedirect("/studormcms/admin/admin.jsp");// 有问题
				}
				break;
			case 2:
				if(request.getRequestURI().indexOf("staff")==-1){
					response.sendRedirect("/studormcms/staff/staff.jsp");
				}
				break;
			case 3:
				if(request.getRequestURI().indexOf("student")==-1){
					response.sendRedirect("/studormcms/student/student.jsp");
				}
				break;
			}
		}
		arg2.doFilter(arg0, arg1);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
